const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const bcconst = require('common/bcconst');
const bccontract = require('common/contract');
const metaFactory = require('../metadata/factory');
const serviceFactory = require('../services/factory');

/*
curl "http://127.0.0.1:7672/webapp/index.php?c=BcService&a=recharge&account_address=0x0c6c7399f1b6b19e96950ef294685bfd0dc46434&passport_address=0x0c6c7399f1b6b19e96950ef294685bfd0dc46434&net_id=13473&amount=100&currency_name=TestToken&order_id=1"
*/
async function recharge(session) {
  try {
    const accountAddress = bcutils.toNormalAddress(session.request('account_address'));
    const passportAddress = bcutils.toNormalAddress(session.request('passport_address'));
    const netId = session.request('net_id');
    const amount = session.request('amount');
    const currencyName = session.request('currency_name');
    const orderId = session.request('order_id');
    const bc = serviceFactory.create('BlockChain');
    {
      const ret = await bc.init(netId);
      if (!ret) {
        session.rspErr(500, 'net_id error');
        return;
      }
    }
    {
      if (!bc.isValidAddress(accountAddress)) {
        session.rspErr(500, 'account_address error');
        return;
      }
      if (!bc.isValidAddress(passportAddress)) {
        session.rspErr(500, 'passport_address error');
        return;
      }
      if (!amount) {
        session.rspErr(500, 'amount error');
        return;
      }
      if (!orderId) {
        session.rspErr(500, 'order_id error');
        return;
      }
    }
    const currencyMeta = bc.getContractByName(currencyName);
    if (!currencyMeta) {
      session.rspErr(500, 'currency meta not found');
      return;
    }
    if (currencyMeta['type'] != 'erc20') {
      session.rspErr(500, 'currency meta type error');
      return;
    }
    const gameMallMeta = bc.getContractByName(bccontract.GameItemMall_INSTANCE_NAME);
    if (!gameMallMeta) {
      session.rspErr(500, 'gamemall meta not found');
      return;
    }
    const currencyAddress = bcutils.toNormalAddress(currencyMeta['address']);
    const gameMallAddress = bcutils.toNormalAddress(gameMallMeta['address']);

    const nowTime = utils.getUtcTime();
    const calls = [];
    {
      const instance = bc.getInstanceByName(currencyName);
      if (!instance) {
        session.rspErr(500, 'currency error');
        return;
      }
      let data = instance.methods.approve(
        gameMallAddress,
        amount).encodeABI();
      calls.push({
        'trans_id' : '',
        'trans_req': {
          'to': currencyAddress,
          'data': data
        }
      });
    }
    {

      const instance = bc.getInstanceByName(bccontract.GameItemMall_INSTANCE_NAME);
      if (!instance) {
        session.rspErr(500, 'gamemall error');
        return;
      }
      const nonce = orderId;
      const signature = await bc.soliditySha3Sign(
        accountAddress,
        passportAddress,
        orderId,
        currencyAddress,
        amount,
        gameMallAddress,
        netId,
        nowTime,
        nonce
      );
      console.log(
        accountAddress,
        passportAddress,
        orderId,
        currencyAddress,
        amount,
        gameMallAddress,
        netId,
        nowTime,
        nonce,
        signature);
      let data = instance.methods.buy(
        passportAddress,
        orderId,
        currencyAddress,
        amount,
        nowTime,
        nonce,
        signature
      ).encodeABI();
      calls.push({
        'trans_id' : '',
        'trans_req': {
          'to': gameMallAddress,
          'data': data
        }
      });
    }

    session.rspData({
      'calls' : calls,
    });
  } catch (e) {
    session.rspErr(1, 1);
    utils.safeDumpErrStack(e);
    console.log(e);
  }
}

function init() {
  app.registerHandler('BcService', 'recharge', recharge);
}

exports.init = init;
